const express = require('express');
const studentCRUD = require('./studentCRUD');

const router = express.Router();


router.get('/post', (req, res) => { res.render('post.html'); })
  .post('/post', (req, res) => {
    res.redirect('/');
  })
  .get(['/students/', '/'], (req, res) => {
    studentCRUD.findAll((error, data) => {
      if (error) {
        res.end(`${error}`);
      } else {
        res.render('index.html', {
          students: data,
          // fruits: JSON.parse(data).students.fruits,
        });
      }
    });
  })
  .get('/students/new', (req, res) => {
    res.render('new.html');
  })
  .post('/students/new', (req, res) => {
    studentCRUD.insert(req.body, (error) => {
      if (error) {
        res.end(error);
      } else {
        res.redirect('/');
      }
    });
  })
  .get('/students/edit', (req, res) => {
    studentCRUD.findOne(req.query.id, (error, data) => {
      if (error) {
        res.end(error);
      } else {
        res.render('edit.html', {
          student: data,
        });
      }
    });
  })
  .get('/students/delete', (req, res) => {
    studentCRUD.deleteStudent(req.query.id, (error) => {
      if (error) {
        res.end(error);
      } else {
        res.redirect('/');
      }
    });
  })
  .post('/students/edit', (req, res) => {
    studentCRUD.update(req.body, (error) => {
      if (error) {
        res.end(error);
      } else {
        res.redirect('/');
      }
    });
  });
module.exports = router;
